#!/bin/python3
#coding=UTF-8

import re
import json
import pandas as pd
from pandas import DataFrame
import requests
import time

input_file = r'./template.xlsx'
interface = "https://api.bilibili.com/x/web-interface/card?mid="
upstat = "https://api.bilibili.com/x/space/upstat?mid="
headers = {
    'Authority': 'api.bilibili.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
    'Cookie': ""
}
with open('cookie.txt', "r", encoding="UTF8") as fb:
    cookie = fb.readlines()[0]
    headers['Cookie'] = cookie.replace('\n', '').replace('\r', '')

df = pd.read_excel(input_file, sheet_name="pytest")
tb_urls = df["链接/UID"]
tb_fans = df["粉丝数"]
tb_vcount = df["视频数"]
tb_like = df["获赞数"]
tb_watch = df["观看数"]
tb_read = df["阅读数"]

lst_name = []
lst_fans = []
lst_vcount = []
lst_like = []
lst_watch = []
lst_read = []

for url in tb_urls:
    is_search = re.search(r"(\d+)", url)
    if is_search:
        uid = is_search[1]
        name = "None"
        fan = vcount = like = watch = read = -1

        time.sleep(0.3)
        infourl = interface + uid
        response = requests.get(infourl, headers=headers)
        if (response.status_code == 200):
            info = json.loads(response.text)
            name = info['data']['card']['name']  # 粉丝数
            fan = info['data']['card']['fans']  # 粉丝数
            vcount = info['data']['archive_count']  # 视频数量
            like = info['data']['like_num']  # 获赞数

        time.sleep(0.3)
        infourl = upstat + uid
        response = requests.get(infourl, headers=headers)
        if (response.status_code == 200):
            info = json.loads(response.text)
            watch = info['data']['archive']['view'] # 播放数
            read = info['data']['article']['view'] # 阅读数

        lst_name.append(name)
        lst_fans.append(fan)
        lst_vcount.append(vcount)
        lst_like.append(like)
        lst_watch.append(watch)
        lst_read.append(read)
        print(f"{name} uid={uid} fan={fan} vcount={vcount} like={like} watch={watch} read={read}")

df["名称"] = lst_name
df["粉丝数"] = lst_fans
df["视频数"] = lst_vcount
df["获赞数"] = lst_like
df["观看数"] = lst_watch
df["阅读数"] = lst_read

timestamp = time.strftime('%Y%m%d_%H%M%S')
output_file = f"{input_file[:-5]}_{timestamp}.xlsx"
DataFrame(df).to_excel(output_file, sheet_name="pytest")
